package com.javasm.adminapi.module.product.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javasm.adminapi.common.R;
import com.javasm.adminapi.common.exception.ExceptionEnum;
import com.javasm.adminapi.common.exception.JavasmException;
import com.javasm.adminapi.module.product.dao.TCategoryDao;
import com.javasm.adminapi.module.product.entity.TBrand;
import com.javasm.adminapi.module.product.entity.TCategory;
import com.javasm.adminapi.module.product.service.TBrandService;
import com.javasm.adminapi.module.product.service.TCategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 商品类型（类目）表(TCategory)表服务实现类
 *
 * @author makejava
 * @since 2025-10-14 22:29:06
 */
@Service("tCategoryService")
public class TCategoryServiceImpl extends ServiceImpl<TCategoryDao, TCategory> implements TCategoryService {

    @Override
    public PageInfo<TCategory> listAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<TCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(TCategory::getSortOrder);
        List<TCategory> list = this.list(queryWrapper);
        return new PageInfo<>(list);
    }

    @Override
    public List<Map<String, Object>> CategoryByIdlist() {
        List<TCategory> list = this.list();
        Map<Integer, TCategory> categoryMap = new HashMap<>();
        List<TCategory> primaryCategories = new ArrayList<>();  // 一级类目

        // 构建映射关系和一级类目列表
        list.forEach(tCategory -> {
            try {
                Integer id = Integer.parseInt(tCategory.getId());
                categoryMap.put(id, tCategory);
                if (tCategory.getParentId() == null || tCategory.getParentId() == 0) {
                    primaryCategories.add(tCategory);
                }
            } catch (NumberFormatException e) {
                System.out.println("Invalid category id: " + tCategory.getId());
            }
        });

        // 构建树形结构
        List<Map<String, Object>> treeData = new ArrayList<>();
        primaryCategories.forEach(primary -> {
            Map<String, Object> primaryNode = new HashMap<>();
            primaryNode.put("id", Integer.parseInt(primary.getId()));
            primaryNode.put("name", primary.getCategoryName());

            List<Map<String, Object>> children = new ArrayList<>();
            list.forEach(child -> {
                if (child.getParentId() != null && child.getParentId() == Integer.parseInt(primary.getId())) {
                    Map<String, Object> childNode = new HashMap<>();
                    childNode.put("id", Integer.parseInt(child.getId()));
                    childNode.put("name", child.getCategoryName());
                    children.add(childNode);
                }
            });

            primaryNode.put("children", children);
            treeData.add(primaryNode);
        });

        return treeData;
    }

    @Override
    public TCategory getBySecondCategoryId(Long secondCategoryId) {

        return this.getOne(new LambdaQueryWrapper<TCategory>().eq(TCategory::getId, secondCategoryId));

    }
    @Resource
    TCategoryDao tCategoryDao;
    @Resource
    TBrandService tBrandService;
    @Override
    public PageInfo<TCategory> queryCategoryByTBarnd(Integer pageNum, Integer pageSize) {
//        List<TCategory> list1 = this.list();
        PageHelper.startPage(pageNum,pageSize);
        List<TCategory> listTCategory =this.list();
        return new PageInfo<>(listTCategory);


    }

    @Override
    public boolean saveInfo(TCategory tCategory) {
        //根据类名查询是否存在
        TCategory byId = this.getById(tCategory.getId());
        if (byId != null){
            throw new JavasmException(ExceptionEnum.Category_Is);
        }
        if (tCategory.getParentId() == null || tCategory.getParentId() == 0){
            tCategory.setLevel(1);
        }else {
            tCategory.setLevel(2);
        }
        tCategory.setIsEnabled(1);
        tCategory.setCreatedTime(new Date());
        boolean save = this.save(tCategory);
        if (!save){
            throw new JavasmException(ExceptionEnum.SQL_Error);
        }
        return true;
    }

    @Override
    public boolean updateByIdinfo(TCategory tCategory) {
        System.out.println("==================================");
        System.out.println(tCategory);

        if (tCategory.getParentId() == 0){
            tCategory.setLevel(1);
            tCategory.setParentId(0);
            tCategory.setUpdatedTime(new Date());
            return this.updateById(tCategory);
        }
        tCategory.setLevel(2);
        tCategory.setUpdatedTime(new Date());
        return this.updateById(tCategory);
    }

    @Override
    public Object removeByIdALL(String id) {
        if (id == null){
            throw new JavasmException(ExceptionEnum.Parameter_Null);
        }
        List<TCategory> list = this.list(new LambdaQueryWrapper<TCategory>().eq(TCategory::getParentId, id));
        if (!list.isEmpty()){
            throw new JavasmException(ExceptionEnum.Category_Is_Not_Null);
        }
        return this.removeById(id);
    }

    @Override
    public TCategory getByName(String categoryName) {
        LambdaQueryWrapper<TCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TCategory::getCategoryName,categoryName);
        return this.getOne(queryWrapper);

    }


}

